<template>
<!-- class="demo-ruleForm" -->
  <el-form label-width="80px" :rules="rules" :model="spuInfo" ref="form"  >
    <el-form-item label="SPU名称" prop="spuName">
      <el-input v-model="spuInfo.spuName" placeholder="SPU名称"></el-input>
    </el-form-item>
    <el-form-item label="品牌" prop="tmId">
      <el-select v-model="spuInfo.tmId" placeholder="请选择">
        <el-option v-for="trademark in trademarkList" :key="trademark.id"  :label="trademark.tmName" :value="trademark.id">
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述" prop="description">
      <el-input type="textarea" :rows="4" placeholder="SPU描述" v-model="spuInfo.description"></el-input>
    </el-form-item>
    <el-form-item label="SPU图片">
      <el-upload action="/dev-api/admin/product/fileUpload" list-type="picture-card"
        :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload" :file-list="spuInfo.spuImageList">
        <i class="el-icon-plus"></i>
      </el-upload>
      <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
    </el-form-item>
    <el-form-item label="销售属性" prop="saleAttr">
      <el-select  :placeholder="unUsed" v-model="attr_name_id">
        <el-option v-for="baseSaleAttr in unUsedBaseSaleAttrList" :key="baseSaleAttr.id"  
        :label="baseSaleAttr.name" :value="`${baseSaleAttr.name}-${baseSaleAttr.id}`">
        </el-option>
      </el-select>
      <el-button type="primary" icon="el-icon-plus" @click="addSaleAttr" :disabled="attr_name_id?false:true">添加销售属性</el-button>
      <el-table :data="spuInfo.spuSaleAttrList" border style="margin-top:20px">
        <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
        <el-table-column label="属性名" align="center" prop="saleAttrName"></el-table-column>
        <el-table-column label="属性值名称列表" align="center">
            <template #default="{row,$index}">
                <el-tag :key="item.id" v-for="(item,index) in row.spuSaleAttrValueList" closable :disable-transitions="false" @close="handleClose(row,index)">
                    {{item.saleAttrValueName}}
                </el-tag>
                <el-input class="input-new-tag"  v-if="row.inputVisible"  v-model="row.inputValue" :ref="`saveTagInput${$index}`" size="small"
                    @keyup.enter.native="handleInputConfirm(row)"
                    @blur="handleInputConfirm(row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(row,$index)">+添加</el-button>
            </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="{row,$index}">
            <el-popconfirm :title="`确定删除属性${row.saleAttrName}吗？`" @onConfirm="delSaleAttr($index)">
              <HintButton title="删除" slot="reference" icon="el-icon-delete" type="danger" size="mini">
              </HintButton>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="addOrUpdate" :loading="loading">保存</el-button>
      <el-button @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
  export default {
    name: 'AddOrUpdate',
    data() {
      return {
          
        //品牌列表
        trademarkList:[],
        //销售属性列表
        baseSaleAttrList:[],
        spuInfo:{
            id: 210,
            spuName: '',
            description: '',
            category3Id: null,
            tmId: null,
            spuSaleAttrList:[],
            spuImageList:[]
        },
        //上传图片相关
        dialogImageUrl: '',
        dialogVisible: false, 
        //tag相关
        inputValue: '',  
        attr_name_id:'' ,
        loading: false, 
        page:null,
        ruleForm:{
            spuName:'',
        },
        rules: {
        spuName: [ { required: true, message: '请输入SPU名称', trigger: 'blur' },],
        tmId: [{ required: true, message: '请选择品牌', trigger: 'change' }],
        description: [ { required: true, message: '请填写SPU描述信息', trigger: 'blur' }],
        // saleAttr: [ { required: true, message: '请选择销售属性', trigger: 'change' } ],
        }    
      }
    },
  
    computed:{
        //未使用的销售属性
        unUsedBaseSaleAttrList(){
            //spuSaleAttrList已使用的属性值,baseSaleAttrList全部的属性值
            const {baseSaleAttrList,spuInfo:{spuSaleAttrList}} = this
                return baseSaleAttrList.filter(item =>{
                    return !spuSaleAttrList.some(attr =>{
                        return +item.id === +attr.baseSaleAttrId
                    })
                })
        },
        //销售属性下拉框的提示文本
        unUsed(){
            return this.unUsedBaseSaleAttrList.length <=0 ? '无':`还剩${ this.unUsedBaseSaleAttrList.length}可选择`
        },
       
    },
    methods: {
        //重置数据
        resetData () {
            this.dialogImageUrl = '' // 大图的url
            this.dialogVisible = false // 标识大图dilaog是否显示

            this.spuId = '' // SPU ID
            this.spuInfo =  { // SPU详情信息对象
                category3Id: null, // 3级分类ID
                spuName: '', // spu名称
                description: '', // spu描述
                tmId: null, // spu的品牌id
                spuSaleAttrList: [], // spu的销售属性列表
                spuImageList: [], // spu图片列表
            }
            this.spuImageList = [] // SPU图片列表
            this.trademarkList = [] // 品牌列表
            this.saleAttrList = [] // 销售属性列表
            this.attrIdAttrName = '' // 用来收集销售属性id与name   id:name
        },
        // 点击保存按钮,发送新增或修改请求
        addOrUpdate(){
            this.$refs.form.validate(async (flag)=>{
                //flag:true验证通过  
                if(flag){
                     this.spuInfo.spuImageList.map(item=>({
                        imgName:item.name,
                        imgUrl:item.url,
                    }))
                    try {
                        this.loading = true
                        await this.$API.spu.addOrUpdate(this.spuInfo)
                        this.loading = false
                        this.$message.success('保存成功')
                    } catch (error) {
                        
                        this.$message.error('网络问题')
                    }finally{
                        this.loading = false
                    }
                     //去列表页面
                    this.$parent.$parent.toShowList()
                    //刷新页面
                    if(this.spuInfo.id){
                        let page = 1
                    }else{
                        let page = this.page
                    }
                    this.$parent.$parent.getSpuByPage(page)
                }
            })
        },
        //删除销售属性
        delSaleAttr(index){
            this.spuInfo.spuSaleAttrList.splice(index,1)
        },
        //添加销售属性
        addSaleAttr(){
        //     {
        //     "id": 10500,
        //     "spuId": 210,
        //     "baseSaleAttrId": 1,
        //     "saleAttrName": "选择颜色",
        //     "spuSaleAttrValueList": [
        //     {
        //         "id": 5885,
        //         "spuId": 210,
        //         "baseSaleAttrId": 1,
        //         "saleAttrValueName": "绿色",
        //         "saleAttrName": "选择颜色",
        //         "isChecked": null
        //      },
            const [saleAttrName,baseSaleAttrId]=this.attr_name_id.split('-')
            const attr = {
                spuId:this.spuInfo.id, 
                saleAttrName,
                baseSaleAttrId,
                spuSaleAttrValueList:[]
            }
            this.spuInfo.spuSaleAttrList.push(attr)
            this.attr_name_id = ''
        },
        //属性值相关
          //删除销售属性值
        handleClose(row,index){
            row.spuSaleAttrValueList.splice(index,1)
        },

        showInput(row,index) {
             if(!row.inputVisible){
                this.$set(row,'inputVisible',true);
            }else{
                row.inputVisible =true
            }
            this.$nextTick(_ => {
                //每一行的ref都不一样
                this.$refs[`saveTagInput${index}`].focus();
            });
        },
        //添加销售属性值
        handleInputConfirm(row) {
            const len = row.spuSaleAttrValueList.filter(item => item.saleAttrValueName === row.inputValue).length
            if(len >=1) {
                this.$message.warning({
                    message:'不能重复',
                    duration:2000
                })
                return
            }
            if(!row.inputValue){
                //row.inputValue可能是undefinedh或''
                row.inputVisible = false;
                return
            }
            // -----------------------
            
        //    spuSaleAttrValueList: [
        //     {
        //         "spuId": 210,
        //         "baseSaleAttrId": 1,
        //         "saleAttrValueName": "绿色",
        //         "saleAttrName": "选择颜色",
        //         "isChecked": null
        //      }
            const {spuId,baseSaleAttrId,saleAttrName} = row
            const attrValue ={
                spuId,
                baseSaleAttrId,
                saleAttrName,
                saleAttrValueName:row.inputValue
            }
            row.spuSaleAttrValueList.push(attrValue)
            row.inputVisible = false;
            row.inputValue=''
        },
        async initAddData(category3Id){
            //清空验证规则
            this.$refs.form.clearValidate()
            this.spuInfo.category3Id = category3Id
             //获取品牌列表
            const {data:trademarkList} = await this.$API.trademark.getTrademarkList()
            //获取销售属性
            const {data:baseSaleAttrList} = await this.$API.spu.getbaseSaleAttrList()
            this.trademarkList = trademarkList
            this.baseSaleAttrList = baseSaleAttrList
        },
        //发请求的函数,点击列表页的编辑按钮调用该函数,发送请求获取数据
        async initData(id,page){
            this.page = page
            //清空验证规则
            this.$refs.form.clearValidate()
            //获取品牌列表
            const {data:trademarkList} = await this.$API.trademark.getTrademarkList()
            //获取销售属性
            const {data:baseSaleAttrList} = await this.$API.spu.getbaseSaleAttrList()
            //获取spu详情
            const {data:spuInfo} = await this.$API.spu.getSpuInfo(id)
            //获取图片列表
            let {data:spuImageList} = await this.$API.spu.getspuImageList(id)
            this.trademarkList = trademarkList
            this.baseSaleAttrList = baseSaleAttrList
            this.spuInfo = spuInfo
            //elementUI规定上传图片列表的格式
            spuImageList = spuImageList.map(item=>({
                name:item.imgName,
                url:item.imgUrl
            }))
            this.spuInfo.spuImageList = spuImageList

        },
        cancel() {
            this.$parent.$parent.toShowList()
        },
        //上传图片相关
        handleRemove(file, fileList) {
            this.spuInfo.spuImageList = fileList;
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        handleAvatarSuccess(response, file, fileList){
          //当图片添加成功之后 将添加成功之后的图片列表同步给spuImageList
          this.spuInfo.spuImageList = fileList;
        },
        beforeAvatarUpload(file) {
          const isJPG = file.type === 'image/jpeg';
          const isLt2M = file.size / 1024  < 30;

          if (!isJPG) {
            this.$message.error({
              message:'上传头像图片只能是 JPG 格式!',
              duration:1000
            });
          }
          if (!isLt2M) {
            //清除上一个提示
            this.$message.closeAll();
            this.$message.error({
              message:"上传头像图片大小不能超过 30kb!",
              duration:1000
            });
          }
          return isJPG && isLt2M;
        }
    }
  }

</script>
<style scoped>
     .el-tag + .el-tag {
        margin-left: 10px;
    }
    .button-new-tag {
        margin-left: 10px;
        height: 32px;
        line-height: 30px;
        padding-top: 0;
        padding-bottom: 0;
    }
    .input-new-tag {
        width: 90px;
        margin-left: 10px;
        vertical-align: bottom;
    }
</style>
